//框架及中间件
var express = require('express');//nodejs常用网页制作框架
var path = require('path');//处理目录的对象
var favicon = require('serve-favicon');//网页图标
var logger = require('morgan');//记录器：在控制台中，显示req请求的信息
var cookieParser = require('cookie-parser');//解析缓存
var bodyParser = require('body-parser');//解析客户端请求的body中的内容
var session = require('express-session');
var MongoStore = require('connect-mongo')(session);//mongodb数据库连接
var flash = require('connect-flash');//flash连接,用于跨页面提示
var multer  = require('multer');//文件上传

//数据库连接配置及路由表
var routes = require('./routes/index');//路由表
var settings = require('./settings');//数据库配置

var fs = require('fs');//文件流
var accessLog = fs.createWriteStream('access.log', {flags: 'a'});//接口日志
var errorLog = fs.createWriteStream('error.log', {flags: 'a'});//错误日志

//-------------------------------------------------------------------------------------

var app = express();

app.set('port', process.env.PORT || 3000); //使用3000端口监听页面
app.set('views', path.join(__dirname, 'views'));//加载模板目录
app.set('view engine', 'ejs');//模板类型为ejs
app.use(favicon(__dirname + '/public/images/favicon.ico'));//加载网页图标
app.use(logger('dev'));//启用开发模式
app.use(logger({stream: accessLog}));//监听接口日志
app.use(bodyParser.urlencoded({ extended: false }));
app.use(multer({//文件上传
  dest: './public/images',
  rename: function (fieldname, filename) {
    return filename;
  }
}));
app.use(cookieParser());
app.use(session({
  secret: settings.cookieSecret,
  key: settings.db,//缓存名称
  cookie: {maxAge: 1000 * 60 * 60},//缓存时间（单位为ms）1h
  store: new MongoStore({
    db: settings.db,
    host: settings.host,
    port: settings.port
  })
}));
app.use(flash());
app.use(express.static(path.join(__dirname, 'public')));

routes(app);

app.use(function (err, req, res, next) { //如果出现异常，写错误日志
  var meta = '[' + new Date() + '] ' + req.url + '\n';
  errorLog.write(meta + err.stack + '\n');
  next();
});

app.listen(app.get('port'), function(){ //服务器启动成功，提示监听的端口等信息
  console.log('Express server listening on port ' + app.get('port'));
});

//捕获404
app.use(function(req, res, next) {
  var err = new Error('Not Found');
  err.status = 404;
  res.render('404');
});

//静态读取文件，进入public目录
app.use(express.static(path.join(__dirname, 'public')));